import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  // 从cookies获取token并记录日志
  const token = request.cookies.get('token')?.value;
  const { pathname } = request.nextUrl;
  
  // 调试信息
  console.log(`[Middleware] 路径: ${pathname}, Token存在: ${!!token}`);

  // 受保护的路由列表，需要登录才能访问
  const protectedRoutes = [
    '/dashboard', 
    '/admin-info', 
    '/user-info', 
    '/approval', 
    '/attendance', 
    '/department-management',
    '/profile',
    '/recruitment/candidates',
    '/recruitment/positions',
    '/recruitment/interviews',
    '/recruitment/offer',
    '/recruitment/positions-management',
    '/recruitment/departments',
  ];
  
  // 公开路由，无需登录即可访问
  const publicRoutes = [
    '/login',
    '/public',
    '/recruitment/offer/accept',
    '/recruitment/public',
    '/api/login', // 允许登录API
  ];

  // 检查是否API请求
  const isApiRequest = pathname.startsWith('/api');
  
  // 如果是API登录请求，总是允许
  if (isApiRequest && pathname === '/api/login') {
    console.log('[Middleware] 允许API登录请求');
    return NextResponse.next();
  }
  
  // 检查是否需要保护的路由
  const isProtectedRoute = protectedRoutes.some(route => pathname.startsWith(route));
  
  // 检查是否公开路由
  const isPublicRoute = publicRoutes.some(route => pathname.startsWith(route));

  // 如果是需要保护的路由，但没有token
  if (!token && isProtectedRoute) {
    console.log(`[Middleware] 拦截未授权访问: ${pathname} -> /login`);
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // 如果有token且尝试访问登录页，重定向到首页
  if (token && pathname === '/login') {
    console.log('[Middleware] 已登录用户重定向: /login -> /dashboard');
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  // 所有其他请求放行
  return NextResponse.next();
}

// 指定哪些路径需要经过middleware处理
export const config = {
  matcher: [
    /*
     * 匹配所有路径除了:
     * 1. /api/login (登录API)
     * 2. 静态文件如 /_next/ 下的文件、图片等
     */
    '/((?!_next/static|_next/image|favicon.ico).*)',
  ],
};